﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.Plan
{
    public partial class PlanAdd : AuthBasePage
    {
        public string sequenceName { get { return "BS_Plan" + DateTime.Now.ToString("yyyy-MM-dd"); } }
        public DataTable PlanDetailDT
        {
            set { Session["PlanDetailDT"] = value; }
            get
            {
                if (Session["PlanDetailDT"] == null)
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["PlanDetailDT"];
                }
            }
        }
        public DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("PlanDetailID");
            dt.Columns.Add("BOMDetailID");
            dt.Columns.Add("IsDirect");
            dt.Columns.Add("MaterialID");
            dt.Columns.Add("MaterialName");
            dt.Columns.Add("Long");
            dt.Columns.Add("Width");
            dt.Columns.Add("Height");
            dt.Columns.Add("OutSide");
            dt.Columns.Add("InSide");
            dt.Columns.Add("Specifications");
            dt.Columns.Add("Unit");
            dt.Columns.Add("MeterWeight");
            dt.Columns.Add("MMNumber");
            dt.Columns.Add("TotalNum");
            dt.Columns.Add("TotalWeight");
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PlanDetailDT = null;
                this.lblPlanID.Text = ClsComm.GetMaxSequenceID(sequenceName, "PL" + DateTime.Now.ToString("yyMMdd"), 3);
                BindDDL();
            }
            txtWorkOrderNo.Attributes.Add("readonly", "true");
            txtCustomerPartNo.Attributes.Add("readonly", "true");
            txtProductID.Attributes.Add("readonly", "true");
            txtProductName.Attributes.Add("readonly", "true");
            txtSpecifications.Attributes.Add("readonly", "true");
            txtUnit.Attributes.Add("readonly", "true");
            txtInSide.Attributes.Add("readonly", "true");
            txtOutSide.Attributes.Add("readonly", "true");
            txtOrderNum.Attributes.Add("readonly", "true");
            txtLastNum.Attributes.Add("readonly", "true");
            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            Master.ValidationGroup = "gSubmit";
        }

        private void BindDDL()
        {
            BindParameterForDDL("ProcessAttribute", ddlProcessAttribute);
            UIHelper.InsertFirstItem(ddlProcessAttribute);
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            string workorderno = this.txtWorkOrderNo.Text.Trim();
            if (!string.IsNullOrEmpty(workorderno))
            {
                DataTable dt = BsPlanBusiness.SelectPlanByWorkOrderNo(workorderno);
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataTable nTable = CreateDT();
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow row = nTable.NewRow();
                        row["PlanDetailID"] = "";
                        row["BOMDetailID"] = CommonMethod.GetString(dr["BOMDetailID"]);
                        row["IsDirect"] = CommonMethod.GetString(dr["IsDirect"]);
                        row["MaterialID"] = CommonMethod.GetString(dr["MaterialID"]);
                        row["MaterialName"] = CommonMethod.GetString(dr["MaterialName"]);
                        row["Specifications"] = CommonMethod.GetString(dr["Specifications"]);
                        row["Unit"] = CommonMethod.GetString(dr["Unit"]);
                        row["Long"] = CommonMethod.GetString(dr["Long"]);
                        row["Width"] = CommonMethod.GetString(dr["Width"]);
                        row["Height"] = CommonMethod.GetString(dr["Height"]);
                        row["OutSide"] = CommonMethod.ConvertToInt(dr["OutSide"]);
                        row["InSide"] = CommonMethod.GetString(dr["InSide"]);
                        row["MeterWeight"] = CommonMethod.GetString(dr["MeterWeight"]);
                        row["MMNumber"] = CommonMethod.GetString(dr["MMNumber"]);
                        decimal totalnum = (CommonMethod.ConvertToDecimal(dr["MMNumber"]) *  CommonMethod.ConvertToDecimal(txtPlanNum.Text.Trim()));
                        row["TotalNum"] = Math.Round(totalnum,2);
                        row["TotalWeight"] = Math.Round((CommonMethod.ConvertToDecimal(dr["MeterWeight"]) * CommonMethod.ConvertToDecimal(txtPlanNum.Text.Trim()) * totalnum), 2);
                        //row["PlanDate"] = "";
                        //row["ActualDate"] = "";
                        row["IsNew"] = "1";
                        row["IsDel"] = "-1";
                        nTable.Rows.Add(row);
                    }
                    PlanDetailDT = nTable.Copy();
                }
            }
            BindGridView();
        }
        private void BindGridView()
        {
            DataView dv = new DataView(PlanDetailDT);
            dv.RowFilter = " IsDel <> '1'";
            //dv.Sort = "BOMDetailID ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel4, "iframeAutoFit();");
        }


        private void AddPro()
        {
            PlanDetailDT = GetAddPro(PlanDetailDT).Copy();
        }

        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblPlanDetailID = gvr.FindControl("lblPlanDetailID") as Label;
                    Label lblBOMDetailID = gvr.FindControl("lblBOMDetailID") as Label;
                    Label lblIsDirect = gvr.FindControl("lblIsDirect") as Label;
                    Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                    Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    Label lblUnit = gvr.FindControl("lblUnit") as Label;
                    Label lblLong = gvr.FindControl("lblLong") as Label;
                    Label lblWidth = gvr.FindControl("lblWidth") as Label;
                    Label lblHeight = gvr.FindControl("lblHeight") as Label;
                    Label lblOutSide = gvr.FindControl("lblOutSide") as Label;
                    Label lblInSide = gvr.FindControl("lblInSide") as Label;
                    Label lblMeterWeight = gvr.FindControl("lblMeterWeight") as Label;
                    Label lblMMNumber = gvr.FindControl("lblMMNumber") as Label;
                    Label lblTotalNum = gvr.FindControl("lblTotalNum") as Label;
                    Label lblTotalWeight = gvr.FindControl("lblTotalWeight") as Label;
                    DataRow[] drs = dtTemp.Select("MaterialID='" + lblMaterialID.Text.Trim() + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["PlanDetailID"] = GetGridViewString(lblPlanDetailID);
                        drs[0]["BOMDetailID"] = GetGridViewString(lblBOMDetailID);
                        drs[0]["IsDirect"] = GetGridViewString(lblIsDirect);
                        drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                        drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["Long"] = GetGridViewString(lblLong);
                        drs[0]["Width"] = GetGridViewString(lblWidth);
                        drs[0]["Height"] = GetGridViewString(lblHeight);
                        drs[0]["OutSide"] = GetGridViewString(lblOutSide);
                        drs[0]["InSide"] = GetGridViewString(lblInSide);
                        drs[0]["MeterWeight"] = GetGridViewString(lblMeterWeight);
                        drs[0]["MMNumber"] = GetGridViewString(lblMMNumber);
                        decimal totalnum = (CommonMethod.ConvertToDecimal(lblMMNumber.Text) * CommonMethod.ConvertToDecimal(txtPlanNum.Text.Trim()));
                        drs[0]["TotalNum"] = Math.Round(totalnum, 2);
                        drs[0]["TotalWeight"] = Math.Round((CommonMethod.ConvertToDecimal(lblMeterWeight.Text) * CommonMethod.ConvertToDecimal(txtPlanNum.Text.Trim()) * totalnum), 2);
                    }
                }
            }
            return dtTemp;
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = PlanDetailDT;
                    DataRow[] dr = dt.Select("MaterialID='" + strCode + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    PlanDetailDT = dt.Copy();
                    BindGridView();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblPlanID.Text.Trim()) && !BsPlanBusiness.IsExistsPlanID(lblPlanID.Text.Trim()))
                {
                    BsPlanEntity entity = new BsPlanEntity();
                    entity.PlanID = GetString(lblPlanID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.BOMID = GetString(hdBOMID);
                    entity.WorkOrderNo = GetString(txtWorkOrderNo);
                    entity.PlanNum = GetDecimal(txtPlanNum);
                    entity.LossNum = GetDecimal(txtLossNum);
                    entity.ProcessAttribute = GetString(ddlProcessAttribute);
                    entity.UseStockNum = GetDecimal(txtUseStockNum);
                    entity.ProduceNum = GetDecimal(txtProduceNum);
                    entity.Remark = GetString(txtRemark);
                    entity.Status = "1";
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID = CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;
                    entity.ModifyDate = DateTime.Now;
                    entity.ModifyUserID = CurrentUser.UserID;
                    entity.ModifyUserName = CurrentUser.UserName;

                    AddPro();

                    if (BsPlanBusiness.SaveOrUpdate(entity, PlanDetailDT, "Save"))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName);
                        base.LogAction(BaseEnum.ActionType.Add, entity.PlanID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../Plan/PlanList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
                else 
                {
                    UIHelper.AlertMessage(this.Page, "生产计划单编号已存在！");
                    ClsComm.SetMaxSequenceID(sequenceName);
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void txtPlanNum_TextChanged(object sender, EventArgs e)
        {
            decimal plannum = CommonMethod.ConvertToDecimal(txtPlanNum.Text);
            decimal lastnum = CommonMethod.ConvertToDecimal(txtLastNum.Text);
            if (plannum > lastnum)
            {
                UIHelper.AlertMessage(this.Page, "计划数量大于剩余数量！");
                return;
            }
            AddPro();
            BindGridView();
        }
    }
}